package com.findviewbydream.evil.eda;

import android.Manifest;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.View;
import android.widget.FrameLayout;

import com.findviewbydream.evil.eda.Bean.MobStationBean;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.EventBus.UserInformationEvent;
import com.findviewbydream.evil.eda.Fragment.Menu.LeftMenu;
import com.findviewbydream.evil.eda.Utils.SAcp;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import okhttp3.Call;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda
 * 时间：16-7-10 下午9:15
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：主界面的基础类
 ********************************************/
public abstract class BaseMainActivity extends AppCompatActivity
{
    private Toolbar toolbar;
    private ObservableScrollView scrollView;
    private FrameLayout container_left;
    private DrawerLayout drawerLayout;

    private ActionBarDrawerToggle barDrawerToggle;

    @LayoutRes
    public abstract int setContentView();/*布局资源文件*/

    public abstract void onCreate();/*待继承类完成的事件*/

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(setContentView());
        initView();

        setDrawerlayout();/*设置侧滑菜单*/
        //setScrollView();/*设置ScrollView对toolbar进行隐藏*/
        onCreate();

        getLocation();/*获取用户位置信息*/
    }

    private void initView()
    {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        //scrollView = (ObservableScrollView) findViewById(R.id.observableScrollView);
        container_left = (FrameLayout) findViewById(R.id.container_left);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        super.onWindowFocusChanged(hasFocus);
    }

    /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>获取用户位置信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
    private void getLocation()
    {
        new Handler().postDelayed(() -> new SAcp()
        {
            private int mcc = -1, mnc = -1, lac = -1, cell = -1;
            private String addr = "";

            @Override
            public void onGranteds()
            {
                TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

                try
                {
                    // 返回值MCC + MNC
                    String operator = telManager.getNetworkOperator();
                    mcc = Integer.parseInt(operator.substring(0, 3));
                    mnc = Integer.parseInt(operator.substring(3));

                    // 中国移动和中国联通获取LAC、CID的方式
                    GsmCellLocation location = (GsmCellLocation) telManager.getCellLocation();
                    lac = location.getLac();
                    cell = location.getCid();
                }
                catch (Exception ignored)
                {
                }
                OkHttpUtils.get().url("http://apicloud.mob.com/station/query")
                        .addParams("key", "173ec9cffbd18")
                        .addParams("mcc", mcc + "")
                        .addParams("mnc", mnc + "")
                        .addParams("lac", lac + "")
                        .addParams("cell", cell + "")
                        .build()
                        .execute(new StringCallback()
                        {
                            @Override
                            public void onError(Call call, Exception e, int id)
                            {

                            }

                            @Override
                            public void onResponse(String response, int id)
                            {
                                if (!response.isEmpty())
                                {
                                    Utils.Log(response);
                                    MobStationBean bean = new Gson().fromJson(response, new TypeToken<MobStationBean>()
                                    {
                                    }.getType());

                                    if (bean.getMsg().equals("success"))
                                        addr = bean.getResult().getAddr();

                                    toNetWork();
                                }
                            }
                        });
            }

            @Override
            public void onDenieds()
            {
                toNetWork();
            }

            /**
             * 用于获取权限成功或不成功时上传数据
             */
            private void toNetWork()
            {
                OkHttpUtils.post().url(Data.IP + "LocationServlet")
                        .addParams("phone", UserData.getUserPhoneNum())
                        .addParams("imei", UserData.getUserIMEI())
                        .addParams("phoneManufacturer", android.os.Build.MANUFACTURER)
                        .addParams("phoneModel", android.os.Build.MODEL)
                        .addParams("androidVersion", android.os.Build.VERSION.RELEASE)
                        .addParams("address", addr)
                        .addParams("mcc", mcc + "")
                        .addParams("mnc", mnc + "")
                        .addParams("lac", lac + "")
                        .addParams("cell", cell + "")
                        .build()
                        .execute(new StringCallback()
                        {
                            @Override
                            public void onError(Call call, Exception e, int id)
                            {

                            }

                            @Override
                            public void onResponse(String response, int id)
                            {

                            }
                        });
            }

        }.getPermissions(Manifest.permission.ACCESS_COARSE_LOCATION), 5000);
    }
    /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>设置侧滑栏>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/

    /**
     * 设置侧滑栏
     */
    private void setDrawerlayout()
    {
        barDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
        {
            @Override
            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                showToolbar();
                EventBus.getDefault().post(new UserInformationEvent(true));/*EventBus ->每次开启都更新侧边栏用户信息*/
            }
        };
        barDrawerToggle.syncState();
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        drawerLayout.addDrawerListener(barDrawerToggle);
    }


    /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>隐藏Toolbar>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/

    private void setScrollView()
    {
        scrollView.setScrollViewCallbacks(
                new ObservableScrollViewCallbacks()
                {
                    @Override
                    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging)
                    {
                    }

                    @Override
                    public void onDownMotionEvent()
                    {
                    }

                    @Override
                    public void onUpOrCancelMotionEvent(ScrollState scrollState)
                    {
                        if (scrollState == ScrollState.UP)
                        {
                            if (toolbarIsShown())
                                hideToolbar();
                        }
                        else if (scrollState == ScrollState.DOWN)
                        {
                            if (toolbarIsHidden())
                                showToolbar();
                        }
                    }
                });
    }

    private boolean toolbarIsShown()
    {
        return ViewHelper.getTranslationY(toolbar) == 0;
    }

    private boolean toolbarIsHidden()
    {
        return ViewHelper.getTranslationY(toolbar) == -toolbar.getHeight();
    }

    private void showToolbar()
    {
        moveToolbar(0);
    }

    private void hideToolbar()
    {
        moveToolbar(-toolbar.getHeight());
    }

    private void moveToolbar(float toTranslationY)
    {
        if (ViewHelper.getTranslationY(toolbar) == toTranslationY)
        {
            return;
        }
        ValueAnimator animator = ValueAnimator.ofFloat(ViewHelper.getTranslationY(toolbar), toTranslationY).setDuration(200);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                float translationY = (float) animation.getAnimatedValue();
                ViewHelper.setTranslationY(toolbar, translationY);
                ViewHelper.setTranslationY((View) scrollView, translationY);
                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) ((View) scrollView).getLayoutParams();
                lp.height = (int) -translationY + getScreenHeight() - lp.topMargin;
                ((View) scrollView).requestLayout();
            }
        });
        animator.start();
    }

    protected int getScreenHeight()
    {
        return findViewById(android.R.id.content).getHeight();
    }

}
